package com.example.cpl.myapplication;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

public class View5 extends AppCompatActivity implements SensorEventListener {

    private LineChartView lineChart;
    List<Line> lineList = new ArrayList<>();
    final List<PointValue> pointValueList = new ArrayList<>();

    private LineChartData data;
    String filename5_1 = "MySharedString_View5_1",filename5_2 = "MySharedString_View5_2",filename5_3 = "MySharedString_View5_3";
    private String change()
    {
        switch(MainActivity.who)
        {
            case 1: return filename5_1;
            case 2: return filename5_2;
            case 3: return filename5_3;
            default:
                return null;
        }
    }
    public int day_new,day_old;
    private int day;
    int bit=0;
    private int t;
    private TextView tv1;
    private Button btn_s,btn_c,btn_clear_his;
    private final String TAG = "StepDcretor";
    // alpha 由 t / (t + dT)计算得来，其中 t 是低通滤波器的时间常数，dT 是事件报送频率
    private final float alpha = 0.8f;
    private long perCalTime = 0;
    private final float minValue = 8.8f;
    private final float maxValue = 10.5f;
    private final float verminValue = 9.5f;
    private final float vermaxValue = 10.0f;
    private final float minTime = 150;
    private final float maxTime = 2000;
    /**
     * 0-准备计时   1-计时中  2-准备为正常计步计时  3-正常计步中
     */
    private int CountTimeState = 0;
    public static int CURRENT_SETP = 0;
    public static int TEMP_STEP = 0;
    private int lastStep = -1;
    // 加速计的三个维度数值
    public static float[] gravity = new float[3];
    public static float[] linear_acceleration = new float[3];
    //用三个维度算出的平均值
    public static float average = 0;
    private Timer timer;
    // 倒计时8秒，8秒内不会显示计步，用于屏蔽细微波动
    private long duration = 0;          //默认8000
    private TimeCount time;
    OnSensorChangeListener onSensorChangeListener;

    public String read_SP_Str(String s,String s1,String file) {
        final SharedPreferences someData = getSharedPreferences(file, 0);
        return  someData.getString(""+s+"",""+s1+"");
    }
    public int read_SP_Int(String s,int s1,String file) {
        final SharedPreferences someData = getSharedPreferences(file, 0);
        return  someData.getInt(""+s+"",s1);
    }
    public void  write_SP_Str(String s,String s1,String file) {
        final SharedPreferences someData = getSharedPreferences(file, 0);
        SharedPreferences.Editor editor = someData.edit();      //让文件 可以编辑
        editor.putString(""+s+"",""+s1+"");
        editor.commit();// 提交修改
    }
    public void  write_SP_Int(String s,int s1,String file) {
        final SharedPreferences someData = getSharedPreferences(file, 0);
        SharedPreferences.Editor editor = someData.edit();      //让文件 可以编辑
        editor.putInt(""+s+"",s1);
        editor.commit();// 提交修改
    }
    public void clear_SP(String file) {
        final SharedPreferences someData = getSharedPreferences(file, 0);
        SharedPreferences.Editor editor = someData.edit();
        editor.clear();
        editor.commit();
    }
    public String getTime(){
        long time=System.currentTimeMillis();   //long now = android.os.SystemClock.uptimeMillis();
        SimpleDateFormat format=new SimpleDateFormat("dd");
        Date d1=new Date(time);
        String t1=format.format(d1);
//        Log.d("TAG",t1);
        return t1;
    }
    @SuppressLint("SetTextI18n")
    private void setSP() {
        int i;
        t= read_SP_Int("参数", 0,change());
        Log.d("TAG","读取的参数t="+""+t+"");
        for (i =1; i <= t ; i++) {

            String day1 = read_SP_Str("天数" + "" + i + "", "0",change());
            String TEMP_STEP1 = read_SP_Str("步数" + "" + i + "", "0",change());
            int day2= Integer.parseInt(day1);
            int TEMP_STEP2= Integer.parseInt(TEMP_STEP1);
            PointValue pointValue3 = new PointValue(day2,TEMP_STEP2);
            pointValueList.add(pointValue3);
            Viewport viewport = initViewPort();
            lineChart.setMaximumViewport(viewport);
            lineChart.setCurrentViewport(viewport);

        }
    }

    private void initView() {
        btn_clear_his=(Button)findViewById(R.id.btn_clear_his);
    btn_s=(Button)findViewById(R.id.btn_s);
    btn_c=(Button)findViewById(R.id.btn_c);
    tv1=(TextView)findViewById(R.id.tv1);
    lineChart = (LineChartView)findViewById(R.id.chart);

}
    public void onSensorChanged(SensorEvent event) {            //监听加速度传感器 计算步数
        Sensor sensor = event.sensor;
        synchronized (this) {
            if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) {

                // 用低通滤波器分离出重力加速度
                gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
                gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
                gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];

                average = (float) Math.sqrt(Math.pow(gravity[0], 2)
                        + Math.pow(gravity[1], 2) + Math.pow(gravity[2], 2));

                if(average <= verminValue){
                    if (average <= minValue)
                    {
                        perCalTime = System.currentTimeMillis();
                    }
                }
                else if (average >= vermaxValue)
                {
                    if (average >= maxValue)
                    {
                        float betweentime = System.currentTimeMillis()
                                - perCalTime;
                        if (betweentime >= minTime && betweentime < maxTime)
                        {
                            perCalTime = 0;
                            if (CountTimeState == 0)
                            {
                                // 开启计时器
                                time = new TimeCount(duration, 1000);
                                time.start();
                                CountTimeState = 1;
                                bit=1;
                                Log.v(TAG, "开启计时器");
                            }
                            else if (CountTimeState == 1)
                            {
                                TEMP_STEP++;
                                tv1.setText(""+TEMP_STEP+"");//       自己加的？
                                write_SP_Str("新步数", ""+TEMP_STEP+"",change());
                                Log.v(TAG, "计步中 TEMP_STEP:" + TEMP_STEP);
                            }
                            else if (CountTimeState==2)
                            {
                                timer = new Timer(true);
                                TimerTask task = new TimerTask(){
                                    public void run(){
                                        if(lastStep == CURRENT_SETP)
                                        {
                                            timer.cancel();
                                            CountTimeState = 0;
                                            lastStep = -1;
//                                            TEMP_STEP = 0;
                                            Log.v(TAG, "停止计步：" + CURRENT_SETP);
                                        }
                                        else
                                        {
                                            lastStep = CURRENT_SETP;
                                        }
                                    }
                                };
                                timer.schedule(task, 0, 2000);
                                CountTimeState = 3;
                            }
                            else if (CountTimeState == 3)
                            {
                                CURRENT_SETP++;
                            }
                        }
                    }
                }

                if (onSensorChangeListener != null) {
                    onSensorChangeListener.onChange();
                }
            }
        }
    }
    public void onAccuracyChanged(Sensor arg0, int arg1) {  //检测传感器精度变化

    }

    public interface OnSensorChangeListener {
        void onChange();
    }

    public OnSensorChangeListener getOnSensorChangeListener() {
        return onSensorChangeListener;
    }

    public void setOnSensorChangeListener(
           OnSensorChangeListener onSensorChangeListener) {
        this.onSensorChangeListener = onSensorChangeListener;
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
//            Log.v(TAG, "计时正常结束start");
            // 如果计时器正常结束，则开始计步
            time.cancel();
            bit=0;
            CURRENT_SETP += TEMP_STEP;
            lastStep = -1;
            CountTimeState = 2;
            Log.v(TAG, "计时正常结束end");
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (lastStep == TEMP_STEP) {
                Log.v(TAG, "onTick 计时停止");
                time.cancel();
                bit=0;
                CountTimeState = 0;
                lastStep = -1;
//                TEMP_STEP = 0;            //清零位置？
            } else {
                lastStep = TEMP_STEP;
            }
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view5);
        initView();


//        Log.v(TAG, "新步数：" + read_SP_Str("新步数", "0",change()));

        TEMP_STEP= Integer.parseInt(read_SP_Str("新步数", "0",change()));
        /**********************       第二天步数清零     *****************************/
        day_new= Integer.parseInt(getTime());
        day_old=Integer.parseInt(read_SP_Str("天","0",change()));
        if(day_new!=day_old){

            day_old=Integer.parseInt(getTime());
            write_SP_Str("天",getTime(),change());
            TEMP_STEP=0;
            tv1.setText("" + 0 + "");

        }
        else {
            tv1.setText("" + TEMP_STEP + "");
        }
        /**********************************************************/



        /************     计步数listener     ****************/
        SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);
        //  获得传感器管理器
        Sensor sensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);         //注册监听器
        if (null != sensor)                             // 监听事件
            sm.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI);//使用传感器更新UI, 建议使用该值SENSOR_DELAY_UI。


        /*************       图表chart设置      ***************/
        List<Line> lines = initLine();
        data = initData(lines);

        lineChart.setLineChartData(data);

        Viewport viewport = initViewPort();
        lineChart.setMaximumViewport(viewport);
        lineChart.setCurrentViewport(viewport);


        setSP();
        /************       按钮listener      ***************/
        btn_s.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                t = t + 1;
                day= Integer.parseInt(getTime());
//                Log.d("TAG", "读取的天数 = " + "" + day + "");
                write_SP_Str("天数" + "" + t + "", getTime(),change());
                write_SP_Str("步数" + "" + t + "", ""+TEMP_STEP+"",change());
                write_SP_Int("参数", t,change());

/******************         按钮按下及时更新图表      ***************************/
                PointValue pointValue3 = new PointValue(day,TEMP_STEP);
                pointValueList.add(pointValue3);
                Viewport viewport = initViewPort();
                lineChart.setMaximumViewport(viewport);
                lineChart.setCurrentViewport(viewport);
/*******************************************************************/
                Toast.makeText(getApplicationContext(), "已记录", Toast.LENGTH_SHORT)
                        .show();//阴影提示框

            }
        });
        btn_c.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) { //清空按钮

                write_SP_Str("新步数", ""+0+"",change());
                TEMP_STEP=0;
                tv1.setText("" + 0 + "");


                Toast.makeText(getApplicationContext(), "已清零", Toast.LENGTH_SHORT)
                        .show();//阴影提示框
            }
        });
        btn_clear_his.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) { //清空按钮

                TEMP_STEP=0;
                tv1.setText("" + 0 + "");

                clear_SP(change());


                Toast.makeText(getApplicationContext(), "已清空图表", Toast.LENGTH_SHORT)
                        .show();//阴影提示框
            }
        });

    }
    @Override
    public void onBackPressed() {       //重写back按键
        super.onBackPressed();
        Log.v(TAG, "按下了back返回键");

        if(bit==1) {                //关闭定时器
            bit=0;
            time.cancel();
            Log.v(TAG, "onTick 计时停止");
            CountTimeState = 0;
        }

        SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);
        sm.unregisterListener(this);                //注销sensor传感器监听,停止记步
//        Log.v(TAG, "注销sensor监听");

        return;
    }
    /**
     * 设置4个边距
     */
    private Viewport initViewPort() {
        Viewport viewport = new Viewport();
        viewport.top = 1000;
        viewport.bottom = 0;
        viewport.left = 0;
        viewport.right = 30;
        return viewport;
    }

    /**
     * 初始化 折线属性
     *
     * @return
     */
    private List<Line> initLine() {

//        PointValue pointValue1 = new PointValue(10,30);
//        pointValueList.add(pointValue1);
//        PointValue pointValue2 = new PointValue(20,20);
//        pointValueList.add(pointValue2);
//        PointValue pointValue3 = new PointValue(30,70);
//        pointValueList.add(pointValue3);
//        PointValue pointValue4 = new PointValue(40,69);
//        pointValueList.add(pointValue4);
//        PointValue pointValue5 = new PointValue(50,64);
//        pointValueList.add(pointValue5);
//        PointValue pointValue6 = new PointValue(60,31);
//        pointValueList.add(pointValue6);
//        PointValue pointValue7 = new PointValue(70,22);
//        pointValueList.add(pointValue7);
//        PointValue pointValue8 = new PointValue(80,100);
//        pointValueList.add(pointValue8);
        Line line = new Line(pointValueList);   //实例化

        line.setColor(getResources().getColor(R.color.colorAccent));    //颜色
        line.setShape(ValueShape.CIRCLE);


        lineList.add(line);
        return lineList;
    }

    /**
     * 初始化数据
     *
     * @return
     */
    private LineChartData initData(List<Line> lines) {
        LineChartData data = new LineChartData(lines);
        //初始化轴
        Axis axisX = new Axis();
        Axis axisY = new Axis().setHasLines(true);
//        axisX.setName("时间");
        //前加字符
//        axisX.setFormatter(new SimpleAxisValueFormatter().setPrependedText("aaaa".toCharArray()));
        //后加字符
//        axisX.setFormatter(new SimpleAxisValueFormatter().setAppendedText("aaaa".toCharArray()));
//        axisX.setFormatter(new SimpleAxisValueFormatter());
//        axisY.setName("步数");
        //设置轴
        data.setAxisYLeft(axisY);
        data.setAxisXBottom(axisX);
        //设置负值 设置为负无穷 默认为0
//        data.setBaseValue(Float.NEGATIVE_INFINITY);

        return data;
    }

    }
